from django.http import HttpResponse
from django.http import HttpResponseForbidden, JsonResponse,HttpResponseBadRequest, HttpResponseServerError
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django_redis import get_redis_connection
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from itsdangerous import BadData
from apps.carts.utils import merge_cart_cookie_to_redis
from apps.goods.models import SKU
from apps.users.utils import generate_verify_email_url
from apps.users.models import User, Address
from apps.oauth.utils import SecretOauth
from celery_tasks.email.tasks import send_verify_email
from meiduo_mall.settings.dev import logger
from utils.response_code import RETCODE
from pymysql import DatabaseError
import json
import re
# Create your views here.
#1.注册页面类视图
class RegisterView(View):
    def get(self, request): #返回注册页面
        return render(request, 'register.html')
    def post(self, request): #接收注册请求发来的的表单格式的数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')
        sms_code = request.POST.get('msg_code')
        redis_code_client = get_redis_connection('sms_code') #连接redis中的短信验证码数据库
        redis_code = redis_code_client.get('sms_%s' %mobile) #获取redis中保存的短信验证码
        if not all([username, password, password2, mobile, allow]): #判断参数是否齐全
            return HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username): #校验用户名的格式
            return HttpResponseForbidden('请输入5-20个字符的用户名')
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password): #校验密码格式
            return HttpResponseForbidden('请输入8-20位的密码')
        if not password == password2: #判断确认密码是否正确
            return HttpResponseForbidden('两次输入的密码不一致')
        if not re.match(r'^1[3-9]\d{9}$', mobile): #校验手机号的格式
            return HttpResponseForbidden('请输入正确的手机号码')
        if not allow == 'on': #判断是否同意用户协议
            return HttpResponseForbidden('请勾选用户协议')
        if redis_code is None: #判断redis中是否存在短信验证码
            return render(request, 'register.html', {'sms_code_errmsg':'短信验证码过期了'})
        if sms_code != redis_code.decode(): #判断redis数据库的短信验证码与输入的是否相同,注意redis中取出的数据为bytes类型
            # return render(request, 'register.html', {'sms_code_errmsg':'输入的短信验证码有误'})
            return HttpResponseForbidden('输入的短信验证码有误')
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile) #在mysql中创建用户
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg':'注册失败'})
        login(request, user) #状态保持
        response = redirect(reverse('contents:index'))#注册成功时重定向至首页
        response.set_cookie('username', user.username, max_age=3600*24*15) #设置cookie
        return response
#2.判断用户名是否重复注册
class UsernameCountView(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code':RETCODE.OK, 'errmsg':'OK', 'count':count})
#3判断手机号是否重复注册
class MobileCountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code':RETCODE.OK, 'errmsg':'OK', 'count':count})
#4.用户登录
class LoginView(View):
    def get(self, request): #登录页请求
        return render(request, 'login.html')
    def post(self,request): #接收三个参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')
        if not all([username, password]):
            return render(request, 'login.html', {'account_errmsg':'输入信息不全'})
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return render(request, 'login.html', {'account_errmsg':'请输入5-20位字符的用户名'})
        if not re.match(r'^[0-9a-zA-Z]{8,20}$', password):
            return render(request, 'login.html', {'account_errmsg':'请输入8-20位字符的密码'})
        user = authenticate(username=username, password=password) #用django自带的认证,验证用户名和密码
        if user is None:
            return render(request, 'login.html', {'account_errmsg':'用户名或密码错误'})
        login(request, user)
        if remembered != 'on':
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)
        next = request.GET.get('next')
        if next:
            response = redirect(next)
        else:
            response = redirect(reverse('contents:index'))
        # 合并购物车
        response = merge_cart_cookie_to_redis(request=request, user=user, response=response)
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)  # 设置cookie
        return response
#5.退出登录
class LogoutView(View):
    def get(self,request):
        logout(request) #清理session
        response = redirect(reverse('users:login')) #退出登录,重定向到登录页
        response.delete_cookie('username')
        return response
#6.用户中心
class UserInfoView(LoginRequiredMixin, View):
    def get(self, request):
        context = { #提供个人信息界面
            'username':request.user.username,
            'mobile':request.user.mobile,
            'email':request.user.email,
            'email_active':request.user.email_active
        }
        return render(request, 'user_center_info.html', context=context)
#7.绑定邮箱
class EmailView(LoginRequiredMixin, View):
    def put(self, request):
        json_str = request.body.decode()
        json_dict = json.loads(json_str)
        email = json_dict.get('email')
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return HttpResponseForbidden('参数email有误')
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':RETCODE.DBERR, 'errmsg':'添加邮箱失败'})
        # verify_url = 'http://www.itcast.cn'
        verify_url = generate_verify_email_url(request.user)
        send_verify_email.delay(email, verify_url)
        return JsonResponse({'code':RETCODE.OK, 'errmsg':'添加邮箱成功'})
#8.验证邮箱
class VerifyEmailView(View):
    def get(self, request):
        token = request.GET.get('token')
        if not token:
            return HttpResponseBadRequest('缺少token')
        try:
            token_dict = SecretOauth().loads(token)
        except BadData:
            return None
        try:
            user = User.objects.get(id=token_dict['user_id'], email=token_dict['email'])
        except Exception as e:
            logger.error(e)
            return None
        if not user:
            return HttpResponseForbidden('无效的token')
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return  HttpResponseServerError('激活邮件失败')
        return redirect(reverse('users:info'))
#9.查询收货地址
class AddressView(LoginRequiredMixin, View):
    def get(self, request):
        addresses = Address.objects.filter(user=request.user, is_deleted=False)
        address_dict_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }
            address_dict_list.append(address_dict)
        context = {
            'default_address_id': request.user.default_address_id,
            'addresses': address_dict_list
        }
        return render(request, 'user_center_site.html', context)
#10.增加收货地址
class CreateAddressView(LoginRequiredMixin, View):
    def post(self, request):
        """实现新增地址逻辑"""
        # 判断是否超过地址上限：最多20个
        # count = Address.objects.filter(user=request.user, is_deleted=False).count()
        count = request.user.addresses.filter(is_deleted=False).count()
        if count >= 20:
            return JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超过地址数量上限'})
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return HttpResponseForbidden('参数email有误')
        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title = receiver,
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )
            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '新增地址失败'})
        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 响应保存结果
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '新增地址成功', 'address':address_dict})
#11.修改和删除收货地址
class UpdateDestroyAddressView(LoginRequiredMixin, View):
    def put(self, request, address_id): #修改收货地址
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return HttpResponseForbidden('参数email有误')
        # 判断地址是否存在,并更新地址信息
        try:
            # Address.objects.filter(id=address_id).update(
            #     user = request.user,
            #     title = receiver,
            #     receiver = receiver,
            #     province_id = province_id,
            #     city_id = city_id,
            #     district_id = district_id,
            #     place = place,
            #     mobile = mobile,
            #     tel = tel,
            #     email = email
            # )
            address = Address.objects.get(id=address_id)
            address.user = request.user
            address.title = receiver
            address.receiver = receiver
            address.province_id = province_id
            address.city_id = city_id
            address.district_id = district_id
            address.place = place
            address.mobile = mobile
            address.tel = tel
            address.email = email
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新地址失败'})
        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 响应更新地址结果
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '更新地址成功', 'address': address_dict})
    def delete(self, request, address_id): #删除收货地址
        try:
            address = Address.objects.get(id=address_id) #查询要删除的地址
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':RETCODE.DBERR, 'errmsg':'删除地址失败'})
        return JsonResponse({'code':RETCODE.OK, 'errmsg':'删除地址成功'})
#12.设置默认地址
class DefaultAddressView(View):
    def put(self, request, address_id):
        try:
            address = Address.objects.get(id = address_id)
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code':RETCODE.DBERR, 'errmsg':'设置默认地址失败'})
        return JsonResponse({'code':RETCODE.OK, 'errmsg':'设置默认地址成功'})
#13.修改地址标题
class UpdateTitleView(View):
    def put(self, request, address_id):
        # 接收参数：地址标题
        title = json.loads(request.body.decode()).get('title')
        try:
            address = Address.objects.get(id=address_id)
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置地址标题失败'})
        # 4.响应删除地址结果
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '设置地址标题成功'})
#14.修改密码
class ChangePasswordView(LoginRequiredMixin, View):
    def get(self, request):
        return render(request, 'user_center_pass.html')
    def post(self, request):
        #接收参数
        old_password = request.POST.get('old_pwd')
        new_password = request.POST.get('new_pwd')
        new_password2 = request.POST.get('new_cpwd')
        #校验参数
        if not all([old_password, new_password, new_password2]):
            return HttpResponseForbidden('缺少必传参数')
        if not request.user.check_password(old_password):
            return render(request, 'user_center_pass.html', {'origin_pwd_errmsg':'原始密码错误'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return HttpResponseForbidden('密码最少8位，最长20位')
        if new_password != new_password2:
            return HttpResponseForbidden('两次输入的密码不一致')
        #需求处理
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return render(request, 'user_center_pass.html', {'change_pwd_errmsg': '修改密码失败'})
        logout(request)
        response = redirect(reverse('users:login'))
        response.delete_cookie('username')
        #响应结果
        return response
#15.记录用户浏览记录
class UserBrowseHistory(LoginRequiredMixin, View):
    #1.保存浏览记录
    def post(self, request):
        # 1.接收json参数,获取sku_id
        sku_id = json.loads(request.body.decode()).get('sku_id')
        # 2.根据sku_id 查询sku
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('商品不存在!')
        # 3.如果有sku,保存到redis
        history_redis_client = get_redis_connection('history')
        history_key = 'history_%s' % request.user.id
        redis_pipeline = history_redis_client.pipeline()
        # 3.1 去重
        redis_pipeline.lrem(history_key, 0, sku_id)
        # 3.2 存储
        redis_pipeline.lpush(history_key, sku_id)
        # 3.3 截取 5个
        redis_pipeline.ltrim(history_key, 0, 4)
        redis_pipeline.execute()
        # 响应结果
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
    #2.查看浏览记录
    def get(self, request):
        # 获取Redis存储的sku_id列表信息
        redis_conn = get_redis_connection('history')
        sku_ids = redis_conn.lrange('history_%s' %request.user.id, 0, -1)
        # 根据sku_ids列表数据，查询出商品sku信息
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'skus': skus})